// xc_lshop/shop/user/vip/editinfor.js
var actmember = require('../../../../xc/model/member')
var app = getApp();
Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    /*表单验证是否通过数据*/
    vildfield: {
      headimgurl: true,
      nickname: true,
      name: true,
      sex: true,
      phone: true,
    },
    /* 表单提交的数据*/
    formdata: {},
    // 图片数据
    fileList: [],
    calendarshow: false,
    minDate: new Date(1950, 0, 1).getTime(),
    currentDate: new Date(1990, 0, 1).getTime(),
    maxDate: new Date().getTime(),
  },
  //加载完成加载
  xcloaddata: function (options, config) {
    console.log("config")
    console.log(config)
    this.setData({
      vipconfig:config.vip
    })

  },
  changefrom: function (ev) {
    var val = ev.detail
    var field = ev.currentTarget.dataset.field;
    // console.log("this.data.model")
    // console.log(this.data.model)
    console.log(field)
    console.log(val)
    var name=["formdata."+field]
    if(val && val[0]){
      this.setData({
        [name]:val[0]
      })
    }else{
      this.setData({
        [name]:""
      })
    }

    // if(field=='videoimg' || field=='videourl'){
    //   this.setval(this.data.model, field, val[0])

    // }else{
    //   this.setval(this.data.model, field, val)

    // }

    this.checkRule(field)


  },
  afterlogin(options, configdata, userinfo) {
    if (userinfo['memberinfo']) {
      var dataarray = ['headimgurl',"nickname",'name','sex',"phone","birthday"]
      var data = {};
      var fileList = [];
      for (var i in dataarray) {
        
        if (dataarray[i] == 'headimgurl') {
          var image = {};
          image['url'] = userinfo['memberinfo'][dataarray[i]];
          image['deletable'] = true;
          image['isImage']=true;
          fileList.push(image)
          data['headimgurl']=userinfo['memberinfo'][dataarray[i]]
        } else {
          data[dataarray[i]] = userinfo['memberinfo'][dataarray[i]]
        }
      }
    

      this.setData({
        formdata: data,
        fileList: fileList,
        memberinfo: userinfo['memberinfo']
      })
    } else {
      this.error("尚未注册", true)
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  
  onsexChange(e){
    
     this.setData({
       'formdata.sex':e.detail
     })
     this.checkForm("sex")
  },
  // 表单提交
  formSubmit: function (e) {
    var valid = this.checkForm();
    console.log(valid)
    if (valid) {
      actmember.editvip(this.data.formdata).then(function (res) {
        if (res["status"] == 1) {
          // var updatemodel = {};
          // updatemodel["member.memberinfo.isvip"] = 1
          // updatemodel["member.memberinfo.vipinfo"] = res["obj"]
    
          app.globalData.member = res["obj"]
          wx.showToast({
            icon: "none",
            title: '修改成功',
          })

          wx.navigateBack({
            delta:1
          })  
        } else {
          wx.showToast({
            icon: "error",
            title: '修改失败',
          })
        }
      })
    }
    console.log(valid)
  },
 
  //上传图片--传图
  afterRead: function (e) {
    var app = getApp();
    var that = this;
    var url = app.util.url("entry/wxapp/sys_upload");
    var sessionid = wx.getStorageSync('userInfo').sessionid;
    url = url + '&op=upimg';
    var state = this.getUrlParam(url, 'state');
    if (!state && sessionid) {
      url = url + '&state=we7sid-' + sessionid
    }
    var nowPage = getCurrentPages();
    if (nowPage.length) {
      nowPage = nowPage[getCurrentPages().length - 1];
      if (nowPage && nowPage.__route__) {
        url = url + '&m=' + nowPage.__route__.split('/')[0];
      }
    }
    var tempFiles = e.detail.file;
    wx.uploadFile({
      url: url, //仅为示例，非真实的接口地址
      filePath: tempFiles.path,
      name: 'file',
      formData: {
        'op': 'upimg'
      },
      success: function (res) {
        var reslut = JSON.parse(res.data);
        if (reslut['status'] == 1) {
          var image = {};
          image['url'] = reslut["obj"].fullpath;
          image['deletable'] = true;
          var newFiles = that.data.fileList.concat(image);
          that.setData({
            'formdata.headimgurl':reslut["obj"].fullpath,
            fileList: newFiles
          });
          // that.data.formdata["fileList"] = newFiles
          that.checkForm("headimgurl")
        }
      },
      fail: function (res) {
    
      }
    })
    // })
  },
  //上传图片--删图
  deleteImg: function (e) {
    var that = this;
    var index = e.detail.index;
    var files = this.data.fileList;
    files.splice(index, 1);
    this.setData({
      'formdata.headimgurl':"",
      fileList: files,
    });
    this.checkForm("headimgurl")
  },
  //上传图片--传图--获取url
  getUrlParam(url, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
    var r = url.split('?')[1].match(reg); //匹配目标参数  
    if (r != null) return unescape(r[2]);
    return null; //返回参数值  
  },
  // 选择地址--点击选择
  selectArea: function () {
    this.selectComponent("#picker").setinitdata();
  },
  // 选择地址--点击确认
  chooseaddress: function (e) {
    var data = e.detail;
    this.setData({
      "formdata.region": data
    })
  },
  // 获取手机号
  getPhoneNumber(e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var encryptedData = e.detail.encryptedData;
    // if (!encryptedData) {
    //   return;
    // }
    var iv = e.detail.iv;
    var code = e.detail.code;

    var app = getApp();
    app.toolv2.getphone(encryptedData, iv,code).then(function (data) {
      if (data["code"] == "success") {
        var upatemodel = {};
        upatemodel["phone"] = data["obj"].phoneNumber;
        that.setData(upatemodel);
        that.data.formdata["phone"] = data["obj"].phoneNumber
        that.checkForm("phone")
      }
    });
  },
  // 同意
  onChange(event) {
    var dataset = event.target.dataset
    this.setData({
      'formdata.checked': event.detail,
    });

    this.checkForm(dataset.field)
  },
  //验证规则
  checkRule(field) {
    var updatemodel = {};
    if (field == "sex") {
      updatemodel['vildfield.' + field] = (this.data.formdata[field]==1 || this.data.formdata[field]==2) ? true : false;
    } else {
      updatemodel['vildfield.' + field] = this.data.formdata[field] ? true : false;
    }
    this.setData(updatemodel)
  },
  //验证表单
  checkForm: function (field) {
    var error = true;
    if (field) {
      this.checkRule(field)
    } else {
      [ "name", "nickname", "phone", "headimgurl", "sex"].forEach(item => {
        this.checkRule(item)
        if (!this.data.vildfield[item]) {
          error = false;
        }
      })
    }
    return error;
  },
  //监听input输入
  watchInput: function (e) {
    var dataset = e.target.dataset
    this.data.formdata[dataset.field] = e.detail
    this.checkForm(dataset.field)
  },
 //------选择生日---start------
 chooseBirth(e) {
  this.setData({
    calendarshow: true
  })
},
formatDate(date) {
  date = new Date(date);
  return `${date.getFullYear()}-${this.changenum(date.getMonth() + 1)}-${this.changenum(date.getDate())}`;
},
changenum(num) {
  if (num < 10) {
    num = "0" + num
  }
  return num
},
onCalendarConfirm(e) {
  var val = e.detail;
  this.setData({
    'formdata.birthday': `${this.formatDate(val)}`,
  })
  this.onCalendarClose()
  this.checkForm('birthday')

},
onCalendarClose() {
  this.setData({
    calendarshow: false
  })
},
//------选择生日---end------
})